<?php

namespace app\admin\model\caijiaku;

use think\Model;
use traits\model\SoftDelete;
use think\Db;
use think\Log;

class MaterialInventoryTemp extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'material_inventory_temp';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
    ];
    

    public function base($query)
    {
        $query->alias('material_inventory_temp')->where('material_inventory_temp.caijiakuid',CAIJIAKU_ID)->useSoftDelete($this->deleteTime);
    }

    public static function init()
    {
        self::beforeInsert(function ($row) {
            $row->caijiakuid = CAIJIAKU_ID;
        });
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function importFormal($data, $adminid)
    {
        if (empty($data)) return ['status' => 0, 'msg' => '没有需要导入的数据'];
        $insertData = [];
        $updateData = [];
        foreach ($data as $key => $value) {
            if (!empty($value['isimport'])) continue;
            $row = $value;
            $updateData[] = [
                'id' => $value['id'],
                'isimport' => 1,
                'import_adminid' => $adminid,
                'import_time' => time(),
            ];
            $row['temp_id'] = $value['id'];
            $row['createtime'] = time();
            $row['updatetime'] = time();
            unset($row['id'], $row['isimport'], $row['import_adminid'], $row['import_time']);
            //判断主库是否已存在
            $where = [
                'project_name' => $row['project_name'],
                'title' => $row['title'],
                'own_spec' => $row['own_spec'],
                'unit' => $row['unit'],
                'price' => $row['price'],
                'deletetime' => null
            ];
            $exist = Db::name('material_inventory')->where($where)->count();
            if ($exist) {
                continue;
            }
            $insertData[] = $row;
        }
        if (empty($insertData)) return ['status' => 0, 'msg' => '没有需要导入的数据或数据已存在'];
        try{
            $this->startTrans();
            $updateRes = $this->allowField(true)->saveAll($updateData);
            $insertRes = Db::name('material_inventory')->insertAll($insertData);
            if (!$updateRes || !$insertRes) {
                $this->rollback();
                return ['status' => 0, 'msg' => '导入失败'];
            }
            $this->commit();
            return ['status' => 1, 'msg' => '导入成功'];
        } catch (\Exception $e) {
            $this->rollback();
            Log::error('临时库导入正式库报错：'.$e->getMessage());
            return ['status' => 0, 'msg' => $e->getMessage()];
        }
    }
}
